var page = 1;
Page({

  data: {
    noInfo: false,
    loading: false,
  },

  cancel(data) {
    var out_trade_no, total_fee;
    this.data.orders.forEach(e => {
      if (e.id_kd_order == data.currentTarget.id) {
        out_trade_no = e.order_number,
        total_fee = e.price * 100;
        return;
      }
    });
    wx.call("payment", {
      command: "refund",
      out_trade_no: out_trade_no,    // 商户订单号
      out_refund_no: out_trade_no + 're',  // 商户退款订单号，要求商户内唯一
      total_fee: total_fee,  // 原单订单金额(单位是分)
      refund_fee: total_fee,
      refund_desc: `订单被取消`
    }, res => {
      wx.post('withdrawOrder', {
        unionid: wx.appData.user.unionid,
        id_kd_order: data.currentTarget.id
      }, res => {
        if (res.ok) {
          wx.toast("订单已取消", "success", 0);
          this.onLoad();
        } else {
          wx.toast(res.msg, 0, 0);
        }
      })
      this.onLoad();
    }, "正在检查订单")
  },
  
  receive(e) {
    wx.post('confirmOrder', {
      unionid: wx.appData.user.unionid,
      id_kd_order: e.currentTarget.id
    }, res => {
      this.onLoad();
      if (res.ok)
        wx.toast("已成功收货", "success", 0);
      else 
        wx.toast(res.msg, 0, 0);
    }, "正在检查订单")
  },
  
  call(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.id,
    })
  },

  onLoad() {
    page = 1;
    this.setData({ loading: true, noInfo: false });
    wx.post('getOrderByUser', {
      unionid: wx.appData.user.unionid
    }, res => {
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
      if (!res.ok) {
        this.setData({ noInfo: true });
        return 0;
      }
      res.data.forEach(e => {
        e.id = (Array(6).join(0) + e.id_kd_order).slice(-6);
        e.price = parseFloat(e.price).toFixed(2);
      })
      this.setData({ orders: res.data });
      ++page;
    })
  },

  onPullDownRefresh() {
    this.onLoad();
  },
  
  onReachBottom: function () {
    if (this.data.noInfo) return;
    this.setData({ loading: true });
    wx.post('getOrderByUser', {
      unionid: wx.appData.user.unionid,
      page: page,
    }, res => {
      this.setData({ loading: false });
      if (!res.ok) {
        this.setData({ noInfo: true });
        return 0;
      }
      res.data.forEach(e => {
        e.id = (Array(6).join(0) + e.id_kd_order).slice(-6);
        e.price = parseFloat(e.price).toFixed(2);
      })
      this.setData({ orders: this.data.orders.concat(res.data)})
      ++page;
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})